package com.datas.controller;

import com.datas.beans.LoginProfile;
import com.datas.db.hibernatebeans.UmsUserLoginToken;
import com.datas.service.LogService;
import com.datas.service.LoginService;
import com.datas.service.api.ApiUserService;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Created by jige0727 on 2017/5/29.
 */
@Controller
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private LogService logService;
    @Autowired
    ApiUserService apiUserService;

    /**
     * 获取token 然后以后的请求要把token放在header里面
     *
     * @param username
     * @param password
     * @param userType
     * @return
     */
    @ResponseBody
    @RequestMapping(value = {"/cas/oauth2.0/accessToken", "/accessToken"}, produces = "application/json;charset=UTF-8")
    public String accessToken(String username, String password, String userType,
                              HttpServletRequest request) {
//        LoggerFactory.getLogger(getClass()).info("username -> " + username);
//        LoggerFactory.getLogger(getClass()).info("password -> " + password);
//        LoggerFactory.getLogger(getClass()).info("userType -> " + userType);
        if (username == null || password == null || userType == null) {
            return new JSONObject().put("error", "参数错误").toString();
        }
        UmsUserLoginToken token = null;
        JSONObject rolesInfo = new JSONObject();
        if (userType.equals("ums")) {
            token = loginService.getAccessToken(username, password);
            if (token == null) {
                return new JSONObject().put("error", "账号或密码错误").toString();
            }
            rolesInfo = apiUserService.userinfo(token.getAccess_token());
        } else if (userType.equals("expert")) {
            token = loginService.getAccessTokenExpert(username, password);
            if (token == null) {
                return new JSONObject().put("error", "账号或密码错误").toString();
            }
            Map<String, Object> userTypeData = apiUserService.getUserTypeBuToken(token.getAccess_token());
            rolesInfo = apiUserService.userinfoExpert(Integer.parseInt("" + userTypeData.get("users_id")));
        }


        if (token == null) {
            return new JSONObject().put("error", "账号或密码错误").toString();
        }
        logService.saveNewLoginEvent(username, token, request.getRemoteAddr());
        JSONObject res = token.toJson();
        res.put("userinfo", rolesInfo);
        if (rolesInfo.getJSONArray("roles").length() > 0) {
            res.put("role_code", rolesInfo.getJSONArray("roles").getJSONObject(0).get("role_code"));
        }
        return res.toString();
    }

    @ResponseBody
    @RequestMapping(value = {"/cas/oauth2.0/profile", "profile"}, produces = "application/json;charset=UTF-8")
    public String profile(String access_token, String userType, HttpServletResponse response) {
        if (access_token == null) {
            response.setStatus(500);
            return new JSONObject().put("error", "未登录").toString();
        }
        if (userType == null) {
            userType = loginService.getUserTypeByToken(access_token);
        }
        if (userType == null) {
            response.setStatus(500);
            return new JSONObject().put("error", "未登录").toString();
        }
        LoginProfile profile = null;
        if ("ums".equals(userType)) {
            profile = loginService.validProfile(access_token);
        } else if ("expert".equals(userType)) {
            profile = loginService.validProfileExpert(access_token);
        }
        if (profile == null || profile.getUsername() == null || profile.getUsername().isEmpty()) {
            response.setStatus(500);
            return new JSONObject().put("error", "未登录").toString();
        }
        return profile.toJson().toString();
    }
}
